package org.act.xservices.rt.xcontainer.message.formatter;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.act.xservices.rt.xcontainer.framework.IContainerEnvironment;
import org.act.xservices.rt.xcontainer.framework.config.IConfigElement;
import org.act.xservices.rt.xcontainer.framework.config.IConfigurable;

public class MessageFormatterFactory implements IConfigurable{

	private Logger log = IContainerEnvironment.containerLogger;
	
	private Map<String, IMessageFormatter> formattersMap = new HashMap<String, IMessageFormatter>();
	
	
	public void config(IConfigElement formattersElement) throws Exception {

		for (IConfigElement formatterConfig : formattersElement.getChildren()) {

			String contentType = formatterConfig.getAttribute("contentType");
			String formatterClass = formatterConfig.getAttribute("class");

			try {
				if (formatterClass != null && contentType != null) {
					IMessageFormatter formatter = 
						(IMessageFormatter) Class.forName(formatterClass).newInstance();

					formatter.setContentType(contentType);

					addMessageFormatter(formatter);

					log.info("Succeed add MessageFormatter for: " + contentType);
				} else {
					log.info("Error MessageFormatter Parameter: " + contentType 
							+ " " + formatterClass);
				}
			} catch (Exception e) {
				log.info("Failed add MessageFormatter for: " + contentType);
				e.printStackTrace();
			}

		}

	}
	
	
	private void addMessageFormatter(IMessageFormatter builder) {
		formattersMap.put(builder.getContentType(), builder);
	}
	
	public IMessageFormatter getMessageFormatter(String contentType){
		return formattersMap.get(contentType);
	}
	
}
